package com.homer.android.activity.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.homer.android.R;
import com.homer.android.activity.login.LoginThirdPartyDialog.OnLoginListener;
import com.homer.android.activity.main.ConfirmActivity;
import com.homer.android.activity.main.EspUIActivity;
import com.homer.android.activity.register.RegisterActivity;
import com.homer.android.sdk.type.user.EspLoginResult;
import com.homer.android.sdk.type.user.builder.BEspUser;
import com.homer.android.sdk.user.IEspUser;
import com.homer.android.sdk.util.AccountUtil;
import com.homer.android.sdk.util.EspStrings;
import com.homer.push.android.client.ServiceManager;
import com.homer.push.android.client.SystemConfig;



public class LoginActivity extends Activity implements OnClickListener
{
    private IEspUser mUser;
    
    private EditText mPhoneEdt;
    private EditText mPasswordEdt;
    
    private CheckBox mAutoLoginCB;
    
    private Button mLoginBtn;
    private Button mRegisterBtn;
    private Button mQuickUsageBtn;
    private TextView mThirdPartyLoginTV;
    
    private final static int REQUEST_REGISTER = 1;
    
    private LoginThirdPartyDialog mThirdPartyLoginDialog;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.login_activity);
        
        mUser = BEspUser.getBuilder().getInstance();
        //设置应用级的key
        mUser.setAppKey("TEST_KEY");
        
        init();
    }
    
    private void init()
    {
    	mPhoneEdt = (EditText)findViewById(R.id.login_edt_account);
        mPasswordEdt = (EditText)findViewById(R.id.login_edt_password);
        
        mLoginBtn = (Button)findViewById(R.id.login_btn_login);
        mLoginBtn.setOnClickListener(this);
        
        mRegisterBtn = (Button)findViewById(R.id.login_btn_register);
        mRegisterBtn.setOnClickListener(this);
        
        // listen the auto login event
        mAutoLoginCB = (CheckBox)findViewById(R.id.login_cb_auto_login);
        
        mQuickUsageBtn = (Button)findViewById(R.id.login_btn_quick_usage);
        mQuickUsageBtn.setOnClickListener(this);
        
        mThirdPartyLoginTV = (TextView)findViewById(R.id.login_text_third_party);
        mThirdPartyLoginTV.setOnClickListener(this);
        
        mThirdPartyLoginDialog = new LoginThirdPartyDialog(this);
        mThirdPartyLoginDialog.setOnLoginListener(mThirdPartyLoginListener);
    }
    
    @Override
    public void onClick(View v)
    {
        if (v == mLoginBtn)
        {
            login();
        	
//        	try {
//        		Intent intent = NotificationService.getIntent();  
//        		bindService(service, conn, flags)
//                this.startService(intent);
//			} catch (Exception e) {
//				Log.e("login", e.getMessage());
//			}
        	
        }
        else if (v == mRegisterBtn)
        {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivityForResult(intent, REQUEST_REGISTER);
        }
        else if (v == mQuickUsageBtn)
        {
            mUser.loadUserDeviceListDB();
            Intent intent = new Intent(this,EspUIActivity.class/* EspApplication.getEspUIActivity()*/);
            startActivity(intent);
            finish();
        }
        else if (v == mThirdPartyLoginTV)
        {
            mThirdPartyLoginDialog.show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_REGISTER)
        {
            if (resultCode == RESULT_OK)
            {
                String phone = data.getStringExtra(EspStrings.Key.REGISTER_NAME_PHONE);
                String password = data.getStringExtra(EspStrings.Key.REGISTER_NAME_PASSWORD);
                mPhoneEdt.setText(phone);
                mPasswordEdt.setText(password);
            }
        }
    }
    
    private void login()
    {
        final String account = mPhoneEdt.getText().toString();
        final int accountType = AccountUtil.getAccountType(account);
        if (accountType == AccountUtil.TYPE_NONE)
        {
            Toast.makeText(this, R.string.esp_login_email_hint, Toast.LENGTH_SHORT).show();
            return;
        }
        final String password = mPasswordEdt.getText().toString();
        if (TextUtils.isEmpty(password))
        {
            Toast.makeText(this, R.string.esp_login_password_hint, Toast.LENGTH_SHORT).show();
            return;
        }
        new LoginTask(this)
        {
            @Override
            public EspLoginResult doLogin()
            {
                if (accountType == AccountUtil.TYPE_EMAIL)
                {
                    return mUser.doActionUserLoginInternet(account, password);
                }
                else if (accountType == AccountUtil.TYPE_PHONE)
                {
                    return mUser.doActionUserLoginPhone(account, password);
                }
                
                return null;
            }
            
            @Override
            public void loginResult(EspLoginResult result)
            {
                if (result == EspLoginResult.SUC)
                {
                    loginSuccess();
                }
            }
        }.execute();
    }
    
    private OnLoginListener mThirdPartyLoginListener = new OnLoginListener()
    {
        
        @Override
        public void onLoginComplete(EspLoginResult result)
        {
            if (result == EspLoginResult.SUC)
            {
            	
                loginSuccess();
            }
        }
    };
    static ServiceManager serviceManager = null;
    private void loginSuccess()
    {
        SharedPreferences shared = getSharedPreferences(EspStrings.Key.SETTINGS_NAME, Context.MODE_PRIVATE);
        shared.edit().putBoolean(EspStrings.Key.KEY_AUTO_LOGIN, mAutoLoginCB.isChecked()).commit();
        SystemConfig.setSystemNotifyContext(ConfirmActivity.class);
        SystemConfig.setUSERNAME(mUser.getUserName());
        SystemConfig.setPASSWORD(mUser.getUserKey());
        startPushServer();
        
        Intent intent = new Intent(this, EspUIActivity.class/*EspApplication.getEspUIActivity()*/);
        startActivity(intent);
        finish();
    }
    private void startPushServer() {
		// Start the service
		serviceManager = new ServiceManager(this);
		//LoadMessageParams(); // 加载缓存的当前未读消息
		serviceManager.startService();
	}

    public static void stopPushServer() {
		if (null != serviceManager) {
			serviceManager.stopService();
		}
	}
 
}
